package cn.client.ui.view.main.dynamic

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.client.data.localData.dao.UserDao
import cn.client.data.remoteData.bean.DynamicData
import cn.client.data.remoteData.bean.PageSelectByUid
import cn.client.data.remoteData.bean.PublishDynamic
import cn.client.data.remoteData.bean.TakeD
import cn.client.data.remoteData.bean.UserInfoCards
import cn.client.data.remoteData.repository.DynamicRepository
import cn.client.data.userStateManager
import cn.client.ui.view.main.user.UserInfoViewModel
import cn.client.utlis.uriToFileApiQ
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

@HiltViewModel
class DynamicViewModel @Inject constructor(
    private val repository: DynamicRepository,
    private val userDao: UserDao
) : ViewModel() {

    /**
     * 事件管道
     */
    private val _pageEvents = Channel<PageEvent>(Channel.BUFFERED)

    /**
     * 可观察事件数据流
     */
    val pageEvents = _pageEvents.receiveAsFlow()

    /**
     * 可变状态
     */
    var pageStates by mutableStateOf(PageState())
        private set

    // 使用MutableStateFlow来存储动态信息列表
    private val _dynamicDataList = MutableStateFlow<List<DynamicData>>(emptyList())
    val dynamicDataList: StateFlow<List<DynamicData>> = _dynamicDataList

    // 使用MutableStateFlow来存储动态信息
    private val _dynamicDataRes = MutableStateFlow<DynamicData?>(null)
    val dynamicDataRes: StateFlow<DynamicData?> = _dynamicDataRes

    // 使用MutableStateFlow来存储uid
    private val _userId = MutableStateFlow<Int>(-1)
    val userId: StateFlow<Int> = _userId.asStateFlow()


    // 定义本地上传图片状态
    private var _images = mutableStateListOf<Uri>()
    val images: List<Uri> = _images

    /**
     * 收集意图
     */
    fun dispatch(intent: PageIntent) {
        when (intent) {
            is PageIntent.UploadImage -> uploadImage(intent.image)
            is PageIntent.GetDynamicList -> getDynamicList(intent.pageByUid)
            is PageIntent.GetDynamic -> getDynamic((intent.getDynamicById))
            is PageIntent.ToShareDynamicReq -> toShareDynamic(intent.req)
            is PageIntent.GetUser -> getUser(intent.msg)

            else -> {
                Unit
            }
        }
    }

    // 获取动态列表
    private fun getDynamicList(pageByUid: PageSelectByUid) {
        viewModelScope.launch {
            try {
                val res = repository.selectDynamicList(pageByUid)
                if (res.code == 200) {
                    _dynamicDataList.value = res.data ?: emptyList()
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("DynamicViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 获取动态信息
    private fun getDynamic(getDynamicById: TakeD) {
        viewModelScope.launch {
            try {
                val res = repository.selectDynamic(getDynamicById)
                if (res.code == 200) {
                    _dynamicDataRes.value = res.data
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("DynamicViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 上传图片的方法
    private fun uploadImage(image: Uri) {
        viewModelScope.launch {
            try {
                _images.add(image)
                _pageEvents.send(PageEvent.ImageUploaded("上传成功"))
            } catch (e: Exception) {
                _pageEvents.send(PageEvent.UploadError("上传失败：$e"))
            }
        }
    }

    // 上传动态
    private fun toShareDynamic(req: ShareDynamicReq) {
        viewModelScope.launch {
            val imageFiles = req.images.mapNotNull { uri ->
                uriToFileApiQ(uri, req.context)
            }
            try {
                val res = repository.publishDynamic(
                    PublishDynamic(
                        uid = req.uid,
                        content = req.content,
                        category = req.category,
                        images = imageFiles,
                        subject = null
                    )
                )
                if (res.code == 200) {
                    // 上传成功，清空_images列表
                    _images.clear()
                    _pageEvents.send(PageEvent.Success(res.msg))
                } else {
                    _pageEvents.send(PageEvent.Error(res.msg))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("DynamicViewModel", "程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    // 查询本地缓存
    private fun getUser(msg: String){
        Log.d("getUser","消息：$msg")
        viewModelScope.launch {
            userDao.getUser().catch { e ->
                Log.d("DynamicViewModel", "错误：$e")
                _pageEvents.send(PageEvent.GetErr("错误：$e"))
            }.collect { it ->
                if (it != null) {
                    _userId.value = it.uid
                    userStateManager.setUserId(newId =  it.uid)
                    _pageEvents.send(PageEvent.UserRes(uid = it.uid))
                } else {
                    _pageEvents.send(PageEvent.GetErr("查询失败"))
                }
            }
        }
    }
    /**
     * 意图集
     */
    sealed class PageIntent {
        data class GetDynamicList(val pageByUid: PageSelectByUid) : PageIntent()
        data class GetDynamic(val getDynamicById: TakeD) : PageIntent()
        data class ToShareDynamicReq(val req: ShareDynamicReq) : PageIntent()
        data class UploadImage(val image: Uri) : PageIntent()
        data class GetUser(val msg: String) : PageIntent()  // 查询本地缓存

    }


    /**
     * 事件集
     */
    sealed class PageEvent {
        object Idle : PageEvent()
        data class ImageUploaded(val imageUrl: String) : PageEvent()
        data class UploadError(val error: String) : PageEvent()
        data class Error(val error: String) : PageEvent()
        data class Success(val data: Any?) : PageEvent()
        data class UserRes(val uid: Int) : PageEvent()  // 本地缓存
        data class GetErr(val msg: String): PageEvent() // 获取本地缓存失败
    }

    /**
     * 状态集
     */
    data class PageState(
        val uid: Int = -1
    )


    data class ShareDynamicReq(
        val context: Context,
        val uid: Int,
        val content: String,
        val category: Int,
        val images: List<Uri>,
//        val subject: List<Int>
    )

}